package com.example.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.StringReader;

/**
 * @Author yudong
 * @Date 2022/5/24 13:36
 * @description：
 */
@Slf4j
public class XmlUtil {

    public static Object convertXmlStrToObject(Class clazz, String xml) {
        Object xmlObject = null;
        try {
            JAXBContext jc = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            StringReader sr = new StringReader(xml);
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (Exception e) {
            log.error("convert xmlStr to object error, msg <{}>", e.getMessage(), e);
        }
        return xmlObject;
    }

    public static void main(String[] args) throws JAXBException {
        test2();
    }

    private static void test1() {
        String str = "<userInfo>\n" +
                "            <name>admin</name>\n" +
                "            <password>123456</password>\n" +
                "            <email>123@qq.com</email>\n" +
                "        </userInfo>";
        UserInfo o = (UserInfo) XmlUtil.convertXmlStrToObject(UserInfo.class, str);
        System.out.println(o);
    }

    private static void test2() {
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        String str ="<root>\n" +
                "    <userInfo>\n" +
                "        <name>admin</name>\n" +
                "        <password>123456</password>\n" +
                "        <email>123@qq.com</email>\n" +
                "    </userInfo>\n" +
                "</root>";
        MailInfo o = (MailInfo) XmlUtil.convertXmlStrToObject(MailInfo.class, str);
        System.out.println(o);
    }

    private static void test3() throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(MailInfo.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        MailInfo user = (MailInfo) unmarshaller.unmarshal(new File("src/main/resources/mailInfo.xml"));
        System.out.print(user);
    }


}
